const db = require('../config/db.config');
const bcrypt = require('bcryptjs');

class User {
    static async create(userData) {
        const { username, account, password, phone } = userData;
        const hashedPassword = await bcrypt.hash(password, 10);
        
        const [result] = await db.execute(
            'INSERT INTO users (username, account, password, phone) VALUES (?, ?, ?, ?)',
            [username, account, hashedPassword, phone]
        );
        return result.insertId;
    }

    static async findByAccount(account) {
        const [rows] = await db.execute(
            'SELECT * FROM users WHERE account = ?',
            [account]
        );
        return rows[0];
    }

    static async findByPhone(phone) {
        const [rows] = await db.execute(
            'SELECT * FROM users WHERE phone = ?',
            [phone]
        );
        return rows[0];
    }

    static async findById(userId) {
        const [rows] = await db.execute(
            'SELECT user_id, username, account, role, phone, avatar, created_at, updated_at FROM users WHERE user_id = ?',
            [userId]
        );
        return rows[0];
    }

    static async updateProfile(userId, updateData) {
        const allowedFields = ['username', 'phone', 'avatar'];
        const updates = [];
        const values = [];
        
        // 构建更新语句
        Object.keys(updateData).forEach(key => {
            if (allowedFields.includes(key) && updateData[key] !== undefined) {
                updates.push(`${key} = ?`);
                values.push(updateData[key]);
            }
        });
        
        if (updates.length === 0) return false;
        
        values.push(userId);
        const [result] = await db.execute(
            `UPDATE users SET ${updates.join(', ')} WHERE user_id = ?`,
            values
        );
        
        return result.affectedRows > 0;
    }

    static async isPhoneUsedByOthers(phone, userId) {
        const [rows] = await db.execute(
            'SELECT user_id FROM users WHERE phone = ? AND user_id != ?',
            [phone, userId]
        );
        return rows.length > 0;
    }
}

module.exports = User; 